package com.asohofrucol.dto.util;

import java.lang.reflect.Field;

import com.asohofrucol.dto.FormInputDTO;
import com.asohofrucol.model.FormField;
import com.asohofrucol.model.FormFieldInput;

public class FormFieldInputHelper {
	public static FormInputDTO convertToDTO(FormFieldInput formFieldInput) {
		FormInputDTO fieldInputDTO = new FormInputDTO();
		Field[] fields = FormFieldInput.class.getDeclaredFields();
		for(Field field:fields){
			if(!(field.getName().equalsIgnoreCase("formFieldInputAnswers")||field.getName().equalsIgnoreCase("serialVersionUID")))
			try {
				Field fieldDto;
				if(field.getName().equalsIgnoreCase("formField")){
					fieldDto = FormInputDTO.class.getDeclaredField(field.getName()+"Id");
					fieldDto.setAccessible(true);
					fieldDto.set(fieldInputDTO, formFieldInput.getFormField().getId());					
				}else{
					fieldDto = FormInputDTO.class.getDeclaredField(field.getName());
					fieldDto.setAccessible(true);
					field.setAccessible(true);
					fieldDto.set(fieldInputDTO, field.get(formFieldInput));
				}
			} catch (NoSuchFieldException e) {
				e.printStackTrace();
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
			
		}
		return fieldInputDTO;
	}

	public static FormFieldInput converRegisterToEntity(FormInputDTO fiDTO) {
		FormFieldInput formFieldInput = new FormFieldInput();
		Field[] fields = FormFieldInput.class.getDeclaredFields();
		for(Field field:fields){
			if(!(field.getName().equalsIgnoreCase("formFieldInputAnswers")||field.getName().equalsIgnoreCase("serialVersionUID")))
			try {
				if(field.getName().equalsIgnoreCase("formField")){
					Field fieldDto = FormInputDTO.class.getDeclaredField(field.getName()+"Id");
					fieldDto.setAccessible(true);
					//field.setAccessible(true);
					//field.set(formFieldInput, fieldDto.get(fiDTO));	
					formFieldInput.setFormField(new FormField((Long)fieldDto.get(fiDTO)));
				}else{
					Field fieldDto = FormInputDTO.class.getDeclaredField(field.getName());
					field.setAccessible(true);
					fieldDto.setAccessible(true);
					field.set(formFieldInput, fieldDto.get(fiDTO));					
				}

			} catch (NoSuchFieldException e) {
				e.printStackTrace();
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}		
		}		
		
		return formFieldInput;
	}
}
